package bbs.web.servlet;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import bbs.bean.Result;
import bbs.web.newservlet.BaseServlet;

@WebServlet("/cmupload.s")
@MultipartConfig
public class CommitImgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获取前端上传的文件
		Part webfile = request.getPart("file");
		
		//需要存在tomcat服务器根目录下  http://localhost/ 以免返回链接时服务器重新部署项目文件被覆盖
		
		//Servlet中用相对路径读取              --那么绝对路径是："D:\\xxx.xx"此类	
		//对于ServletContext().getRealPath("路径名A");这个方法，无论你的路径名A是什么，
		//ServletContext().getRealPath()方法底层都会在路径名A前拼上当前web应用的硬盘路径
		//只要你的文件在web应用的中的相对路径不变，那么不论你的web应用如何更换服务器环境，
		//都能动态的获取当前服务器环境的绝对文件路径
		String realpath = this.getServletContext().getRealPath("/");
		File file = new File(realpath);
		//获取前端上传文件的文件名
		String FileName = webfile.getSubmittedFileName();
		//获取tomcat下根的目录
		realpath = file.getParentFile().getParentFile().getAbsolutePath();
		//保存文件的目录 
		realpath += "/webapps/ROOT";
		//目录与文件名拼接
		String FilePath = realpath+"/"+FileName;
		//io--写出去  存到拼接出来的目录下
		webfile.write(FilePath);
		String webpath = "/"+FileName;
		
		Result res = new Result(1,"文件上传成功",webpath);
		BaseServlet.toJson(response,res);
	}

}
